<template>
  <div class="feedback-container">
    <div>
      <div style="margin-top: 20px; margin-bottom: 15px">
        <el-button type="primary" plain @click="handleFeedback">我要反馈</el-button>
      </div>
      <el-table
        stripe
        :data="data.tableData"
      >

        <el-table-column prop="issueType" label="问题类型"></el-table-column>
        <el-table-column
          prop="description"
          label="问题描述"
          show-overflow-tooltip
        >
        <template #default="scope">
          <el-button type="text" @click="view(scope.row.description, '问题描述')"
            >查看问题描述</el-button>
        </template>
      </el-table-column>
        <el-table-column prop="status" label="处理状态" />
        <el-table-column prop="backContent" label="处理结果">
          <template #default="scope">
            <el-button type="text" @click="view(scope.row.backContent, '处理结果')"
              >查看处理结果</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-self: end; margin-top: 10px;">
        <el-pagination
          v-if="data.total"
          @current-change="load"
          background
          layout="total, prev, pager, next"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"
        />
      </div>
      <el-dialog
        :title="viewDetailsTitle"
        v-model="data.viewVisible"
        width="50%"
        :close-on-click-modal="false"
        destroy-on-close
      >
        <div
          class="editor-content-view"
          style="padding: 20px"
          v-html="data.backContent"
          v-if="data.backContent"
        ></div>
        <el-empty v-else description="暂未处理" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.viewVisible = false">关 闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <el-dialog
      title="反馈/投诉"
      v-model="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="feedbackForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        size="large"
      >
        <el-form-item label="问题类型" prop="issueType">
          <el-select v-model="formData.issueType" placeholder="请选择问题类型">
            <el-option
              v-for="item in issueTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input
            v-model="formData.contact"
            placeholder="请输入联系方式（选填）"
          ></el-input>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="formData.description"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <!-- <el-form-item label="上传图片" prop="imgs">
          <el-upload
            :action="baseUrl + '/files/upload'"
            :headers="{ 'token': user.token }"
            list-type="picture-card"
            :file-list="formData.imgs"
            :on-remove="handleImageRemove"
            :on-success="handleFileUpload"
            :limit="5"
            :on-exceed="handleImageExceed"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item> -->

      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  <script setup>
import { onBeforeUnmount, ref, reactive, shallowRef } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
const baseUrl = import.meta.env.VITE_BASE_URL
const user = JSON.parse(localStorage.getItem('xm-user') || '{}')

// 编辑器
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: user.token,
  },
  server: baseUrl + '/files/wang/upload',  // 服务端图片上传接口
  fieldName: 'file'  // 服务端图片上传接口参数
}
const handleCreated = (editor) => {
  editorRef.value = editor;
};
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 我要反馈
const feedbackForm = ref(null);
const formData = ref({
  issueType: "",
  contact: "",
  description: "",
  imgs: [],
  userId: ""
});
const formRules = {
  issueType: [{ required: true, message: "请选择问题类型", trigger: "change" }],
  description: [{ required: true, message: "请输入问题描述", trigger: "blur" }],
};
const issueTypes = [
  { label: "功能问题", value: "功能问题" },
  { label: "性能问题", value: "性能问题" },
  { label: "用户体验", value: "用户体验" },
  { label: "我要投诉", value: "我要投诉" },
];


const handleImageRemove = (file, fileList) => {
  for (let i = 0; i < formData.value.imgs.length; i++) {
    if (formData.value.imgs[i].includes(file.name)) {
      formData.value.imgs.splice(i, 1)
    }
  }
};
const handleImageExceed = () => {
  ElMessage.warning("最多只能上传5张图片");
};
const handleFileUpload = (res) => {
  formData.value.imgs.push(res.data)
}
const submitFeedback = async () => {
  feedbackForm.value.validate((valid) => {
    if (valid) {
      const userInfo = JSON.parse(localStorage.getItem('xm-user'))
      formData.value.userId = userInfo.id
      
      // 提交反馈逻辑
      request.post('/feedback/add', formData.value).then(res =>{
        load()
      })
      
      ElMessage.success("反馈已提交，感谢您的支持！");
      dialogVisible.value = false
    } else {
      ElMessage.error("请完善表单信息");
    }
  });
};
const handleFeedback = () => {
  dialogVisible.value = true
  resetForm();
}
const resetForm = () => {
  feedbackForm.value.resetFields();
};


const dialogVisible = ref(false);
const handleClose = () => {
  resetForm();
  dialogVisible.value=false
};
const handleSubmit = () => {
  submitFeedback()
  dialogVisible.value=false
};

// 数据列表
import request from "@/utils/request.js";

const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  title: null,
  ids: [],
  viewVisible: false,
  backContent: null,
});
const viewDetailsTitle = ref()

const view = (backContent, title) => {
  data.backContent = backContent;
  data.viewVisible = true;
  viewDetailsTitle.value = title
};

const load = () => {
  request
    .get("/feedback/list", {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        userId: user.id
      },
    })
    .then((res) => {
      if (res.code === "200") {
        data.tableData = res.data?.list || [];
        data.total = res.data?.total;
      } else {
        ElMessage.error(res.msg);
      }
    });
};
const handleAdd = () => {
  data.form = {};
  data.formVisible = true;
};
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};
const add = () => {
  request.post("/forum/add", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = () => {
  request.put("/forum/update", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const save = () => {
  data.form.id ? update() : add();
};

const del = (id) => {
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "删除确认", {
    type: "warning",
  })
    .then((res) => {
      request.delete("/forum/delete/" + id).then((res) => {
        if (res.code === "200") {
          ElMessage.success("删除成功");
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    })
    .catch((err) => {
      console.error(err);
    });
};
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "删除确认", {
    type: "warning",
  })
    .then((res) => {
      request.delete("/forum/delete/batch", { data: data.ids }).then((res) => {
        if (res.code === "200") {
          ElMessage.success("操作成功");
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    })
    .catch((err) => {
      console.error(err);
    });
};
const handleSelectionChange = (rows) => {
  data.ids = rows.map((v) => v.id);
};

const reset = () => {
  data.title = null;
  load();
};

load();
</script>
<style scoped>
.feedback-container {
  width: 60%;
  margin: 0 auto;
}
</style>